/**
 * @author helio
 */
var StorageCheckView = Ext.extend(BasicPanel,{
	
	initlize : function() {
		
		if(!this.detailsGrid) {
						
			this.detailsStore = new Ext.data.Store({
			    proxy: new Ext.ux.data.PagingMemoryProxy(this.detailsJson),
			    reader: new Ext.data.JsonReader({
					root: 'stocks',
			        fields: ['id', 'pcode','pname', 'sname', {name:'number', type:'float'}, 'punit', {name:'upper_limit', type:'float'}, {name:'lower_limit', type:'float'}]
			    }),
				
				remoteSort:false, 
				sortInfo:{field: 'pcode', direction: 'ASC'}
			});
			
			// create paging bar
			var pagingBar = new Ext.PagingToolbar({
		        pageSize: 25,
		        store: this.detailsStore,
		        displayInfo: true,
				
				plugins: new Ext.ux.ProgressBarPager()
		    });
			
			var editor = new Ext.ux.grid.RowEditor({
		        saveText: '确认',
				cancelText: '取消',
				listeners : {
					'afteredit' : function(rowEditor, obj, record, rowIndex) {
						SALE.Action.modifyProductStocks(function() {
														
							this.showMessage("库存信息修改成功！！！");
														
						}.createDelegate(this), record.data);
						
					}.createDelegate(this)
				}
		    });
			
			// create the grid
			var csm = new Ext.grid.CheckboxSelectionModel();
			
			this.detailsGrid = new Ext.grid.GridPanel({
				store: this.detailsStore,
				columns: [csm,{
					header: "商品编号",
					dataIndex: 'pcode',
					width: 60,
					sortable: true
				}, {
					header: "商品名称",
					dataIndex: 'pname',
					sortable: true
				}, {
					header: "仓库",
					dataIndex: 'sname',			
					width: 60,
					sortable: true
				}, {
					header: "在库数量",
					dataIndex: 'number',			
					width: 60,
					align: 'right',
					renderer: SALE.Utils.stockRenderer.createDelegate(this),
					sortable: true,
					
					editor: new Ext.form.NumberField({
						allowBlank: true
					})
					
				}, {
					header: "单位",
					dataIndex: 'punit',
					width: 45,
					align: 'left',
					sortable: true					
				}, {
					header: "库存上限",
					dataIndex: 'upper_limit',
					width: 50,
					align: 'right',
					sortable: true,
					
					editor: new Ext.form.NumberField({
						allowBlank: true
					})
				}, {
					header: "库存下限",
					dataIndex: 'lower_limit',
					width: 50,
					align: 'right',
					sortable: true,
					
					editor: new Ext.form.NumberField({
						allowBlank: true
					})
				}],
				
				sm: csm,
				
				plugins: [editor],
				
				title: '库存管理/检查库存...',
				
				tbar:[{
            		xtype:'splitbutton',
            		text: '新加库存',
            		iconCls: 'add',
            		handler: this.showInsertStockWin.createDelegate(this),
           			menu: [{
						text: '单品新加', 
						value : "2",
						handler: this.showInsertStockWin.createDelegate(this)
					}, {
						text: '批量新加', 
						value : "1",
						handler: this.showBatchInsertStockWin.createDelegate(this)
					}]
        		}, '-', {
		            text:'删除',
		            tooltip:'删除选中的库存商品',
		            iconCls:'remove',
					handler: this.deleteStock.createDelegate(this)
		        }, '-', {
		            text:'历史记录',
		            tooltip:'商品库存变更历史记录',
		            iconCls:'history',
					handler: TrackRecordStocksView.showNextOperatePanel.createDelegate(this)
		        }, '->', '-', '仓库：', new Ext.form.ComboBox({
        			id: 'storagename',
					tpl: comboxTpl,
			        store: DataStoreUtil.getStorageStore(),
			        displayField:'name',
			        typeAhead: true,
			        mode: 'local',
			        triggerAction: 'all',
			        selectOnFocus:true,
			        width:80,
					listeners: {
						'select': this.queryStocks.createDelegate(this)
					}
					
			    }), '-', new Ext.form.ComboBox({
					id: 'stocksquerytype',
					tpl: comboxTpl,
				    triggerAction: 'all',
				    lazyRender:true,
				    forceSelection:true,
                 	selectOnFocus: true,
				    mode: 'local',
				    width: 100,
				    store: new Ext.data.ArrayStore({
				        id: 0,
				        fields: [
				            'code',
				            'name'
				        ],
				        data: [[1, '按编号查询'], [2, '按名称查询'], [3, '按库存数量查询']]
				    }),
				    valueField: 'code',
				    displayField: 'name',
				    value:2
				}), '-', {
					id: 'stocksqueryvalue',
                	xtype:'trigger',
                    triggerClass: 'x-form-search-trigger',
                    width: 100,
                    onTriggerClick: this.queryStocks.createDelegate(this),
                    listeners: {
        				'show': this.queryStocks.createDelegate(this)
        			}
                }],
				
				bbar: pagingBar,
				
				viewConfig: {
			        forceFit: true,
					enableRowBody:true,
		            showPreview:true
			    },
		
				loadMask: true,
				stripeRows: true,
				border: false,
				autoExpandColumn: 'name',
				layout: 'fit'
			});			
		}
	},
	
	initlizeDataHandler : function(resultJson) {
		this.detailsJson['stocks'] = resultJson.stocks;
		this.detailsStore.load({params:{start:0, limit:25}});
	},
	
	getCorePanel : function() {
		if (!this.detailsGrid) {
			this.initlize();
			SALE.Action.checkStocksJson(this.initlizeDataHandler.createDelegate(this));
		}
		return this.detailsGrid;
	},
	
	queryStocks : function() {
		var querytype = Ext.getCmp('stocksquerytype').getValue();
		var queryvalue = Ext.getCmp('stocksqueryvalue').getValue();
		var storagename = Ext.getCmp('storagename').getValue();
		var condition = {};
		if(querytype == 1) {
			condition.pcode = queryvalue;
		} else if(querytype == 2) {
			condition.pname = queryvalue;
		} else if(querytype == 3) {
			condition.number = queryvalue;
		}
		
		if(storagename) {
			condition.sname = storagename;
		}
		
		if(queryvalue || storagename){
			SALE.Action.checkStocksJson(this.initlizeDataHandler.createDelegate(this), condition);
		}
	},
	
	numberRenderer : function(val,p,r){
		var lower = r.data["lower_limit"] == null || r.data["lower_limit"] == "" ? 0 : r.data["lower_limit"];
		var upper = r.data["upper_limit"] == null || r.data["upper_limit"] == "" ? 9999999999 : r.data["upper_limit"];
		if(val == null || val == "") {
			val = 0;
		}
		if(parseInt(val) >= parseInt(upper) || parseInt(val) <= parseInt(lower)){
			return '<span style="color:red;">' + val + '</span>';
		}else {
			return '<span style="color:green;">' + val + '</span>';
		}
		return val;
	},
	
	showInsertStockWin : function() {
		//if(!this.inputWin) {
				
			this.inputForm = new Ext.FormPanel({
	 			frame: true,
				labelWidth: 55,
				defaultType: 'textfield',
				
				items: [{
					xtype:'fieldset',
					autoHeight:true,
					anchor:'100%',
					layout:'column',
					bodyStyle: 'padding-top:5px;background-color: transparent;',
								
					items: [{
			                columnWidth:.7,
			                layout: 'form',
			                border:false,
			                items: [{
			                	xtype:'trigger',
			                    triggerClass: 'x-form-search-trigger',
			                    name: 'pname',
			                    fieldLabel: '选择商品',
			                    anchor:'100%',
			                    onTriggerClick: function(){
									var pname = this.inputForm.form.findField("pname").getValue();
				   					var condition = {querytype:2,queryvalue:pname};
				   					SALE.window.showProductsSelectWindow(this.productsSelectedHandler.createDelegate(this),condition);
					       		}.createDelegate(this)
			                }, new Ext.form.ComboBox({
								tpl: comboxTpl,
								fieldLabel: '选择仓库',
						        store: DataStoreUtil.getStorageStore(),
						        displayField:'name',
						        typeAhead: true,
						        mode: 'local',
						        forceSelection: false,
						        triggerAction: 'all',
						        emptyText:'输入/选择仓库...',
						        selectOnFocus:true,
								name: 'sname',
								
								anchor:'100%'
							})]
			            }, {
			                columnWidth:.3,
			                layout: 'form',
							labelWidth: 10,
			                border:false,
			                items: [{
								xtype: 'displayfield',
								name: 'pcode',
								anchor: '95%'
							}]
			            }, {
			                columnWidth:.5,
			                layout: 'form',
			                border:false,
			                items: [{
							    xtype:'numberfield',
							    fieldLabel: '在库数量',
							    name: 'number',
							    anchor:'100%'
							}]
			            }, {
			                columnWidth:.5,
			                layout: 'form',
							labelWidth: 5,
			                border:false,
			                items: [{
							    xtype:'displayfield',
							    name: 'punit',
							    anchor:'50%'
							}]
			            }, {
			                columnWidth:1,
			                layout: 'form',
			                border:false,
			                items: [{
							    xtype:'numberfield',
							    fieldLabel: '库存下限',
							    name: 'lower_limit',
							    anchor:'50%'
							}]
			            }, {
			                columnWidth:1,
			                layout: 'form',
			                border:false,
			                items: [{
							    xtype:'numberfield',
							    fieldLabel: '库存上限',
							    name: 'upper_limit',
							    anchor:'50%'
							}]
			            }]
					}],
							
				buttons: [{
			            text: '保存',
						listeners: {
							"click": function(){
								this.synchronizeJson();	
								if (this.formDataJson.pname && this.formDataJson.pname != "") {
									this.saveProductStock();
								}							
							}.createDelegate(this)
						}
			        },{
			            text: '取消',
						listeners:{
							"click":function(){
								this.inputForm.form.reset();
							}.createDelegate(this)
						}
			    }]
			});
				
		 	this.inputWin = new Ext.Window({
		 		
		 		title: '新加库存信息',
				closable: true,	
				collapsible  : true,
				width: 400,
				height: 250,
				plain: true,
				layout: 'fit',
				closeAction :'hide',
					
				items: this.inputForm,
					
				listeners: {
					'show': function() {
						this.synchronizeForm();			
					}.createDelegate(this),
						
					'hide': function() {							
						this.clear();
						SALE.Action.checkStocksJson(this.initlizeDataHandler.createDelegate(this));
					}.createDelegate(this)
				}
		 	});			
		//}
		
		this.inputWin.show();
	},
	
	showBatchInsertStockWin : function() {
						
		this.inputWin = new Ext.Window({
		 		
		 	title: '批量添加库存信息',
			closable: true,	
			collapsible  : true,
			width: 680,
			height: 500,
			layout: 'fit',
			closeAction :'hide',
					
			items: {
				border: false,
				xtype : "stocksbatchinsert"
			},
			
			listeners: {
				'hide': function() {
					SALE.Action.checkStocksJson(this.initlizeDataHandler.createDelegate(this));
				}.createDelegate(this)
			}
		});
		
		this.inputWin.show();
	},
	
	productsSelectedHandler: function(record) {
		this.inputForm.form.findField("pcode").setValue(record.get("pcode"));
		this.inputForm.form.findField("pname").setValue(record.get("pname"));
		this.inputForm.form.findField("punit").setValue(record.get("punit"));
	},
	
	saveProductStock : function() {
		//提交数据
		SALE.Action.insertProductStocks(this.saveSuccessHandler.createDelegate(this), this.formDataJson);
	},
	
	deleteStock : function() {
		this.selectedRecordList = this.detailsGrid.getSelectionModel().getSelections();
		if(this.selectedRecordList.length == 0) {
			this.showMessage('请选择你要删除的数据！！！', '警告');
		} else {
			Ext.MessageBox.confirm('删除确认', '你真的要删除选中的库存信息吗?', function(btn) {
				if (btn == "yes") {
					SALE.Action.deleteProductStocks(this.deleteSuccessHandler.createDelegate(this), this.selectedRecordList);
				}
			}.createDelegate(this));
		}
	}
});

StorageCheckView.showCheckPanel = function(){
	var  storageView = new StorageCheckView();
	
	SALE.App.showOperateTabPanel(storageView.getCorePanel(), "检查库存");
}